import React from 'react';
import style from './style.objective-note';
import { IconButton, Menu, Loading, IconFont, Avatar, Input, Button, Link } from 'sq-ui';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as okrAction from '../../actions/okr.action'
import util from '../../util';
import cx from 'classnames';
import { error, Modal, info, success, TweetInput } from '../../ui-components';
import { checkCurrentAmount } from './Objective';
import moment from 'moment';
import { pageSize as commentsPageSize } from './ObjectiveNote';
import { fetchAtList, clearAtList } from '../../actions/home.action'
const IMAGES_PATH = process.env.NODE_ENV === 'production'? './static/images': './static/src/images'
import CommentDeleteAlert from './plugins/CommentDeleteAlert'
export
const pageSize = 15;

function EditComment(props) {
  const {
    className,
    okrCommentId,
    editable,
    deletable,
    content,
    handleEditComment,
    requestDeleteComment,
  } = props;
  return (
    <ul className={cx(style['comment-actions'], props.className)}>
      {
        editable?
        <li>
          <Link
            label="编辑"
            onClick={() => {
              props.onClose();
              handleEditComment(okrCommentId, content);
            }}
          />
        </li>: null
      }
      {
        deletable?
        <li>
          <Link
            onClick={() => {
              props.onClose();
              requestDeleteComment(okrCommentId);
            }}
            label="删除"
          />
        </li>: null
      }
    </ul>
  );
}

@connect(({ app,okr }) => ({ app,okr }), dispatch => ({actions: bindActionCreators({...okrAction, fetchAtList, clearAtList }, dispatch)}))
class ObjectiveNote extends React.Component {

  state = {
    currentAmount: this.props.currentAmount,
    comment: '',
    editComment: '',
    fetching: false,
    edit: null,
    deleteComment: false,
    deleteCommentNotDetail: false,
    okrCommentId: null,
    editing: false,
  };

  componentWillReceiveProps(props) {
    if (props.objectiveId != this.props.objectiveId) {
      this.props.actions.resetOkrComments();
      this.reFetchComments(null, props);
    }
  }

  componentDidMount() {
    if (!this.props.editObjectiveDetail) {
      this.props.actions.resetOkrComments();
      this.reFetchComments();
    }
  }

  componentWillUnmount() {
    if (!this.props.editObjectiveDetail) {
      this.props.actions.resetOkrComments();
    }
  }

  updateComment(okrCommentId) {
    info('更新中...');
    this.props.actions.updateOkrComment(okrCommentId, { comment: this.state.editComment }, () => {
      success('更新成功!');
      this.reFetchComments(() => {
        this.setState({
          editComment: '',
          edit: null,
        });
      });
    })
  }

  handleCommentChange(e) {
    this.setState({
      editComment: e.target.value,
    });
  }

  handleEditComment(okrCommentId, content) {
    this.setState({
      edit: okrCommentId,
      editComment: content,
    });
  }


  requestDeleteComment(okrCommentId) {
    this.setState({
      deleteComment: true,
      okrCommentId,
    })
  }
  cancelDeleteComment() {
    this.setState({
      deleteComment: false,
      okrCommentId: null,
    })
  }

  deleteComment(id) {
    info('删除中...');
    this.props.actions.deleteOkrComment(typeof id === 'string' ? id : this.state.okrCommentId, () => {
      success('删除成功!');
      this.reFetchComments();
    });
    this.cancelDeleteComment();
  }

  reFetchComments(cb, props) {

    const args = this.props.editObjectiveDetail ? {
      pageSize,
      pageNumber: 1,
    } : {
      pageSize,
      pageNumber: 1,
      keyResultId: this.props.keyResultId,
    };

    // 详情页从url取
    let objectiveId = this.props.detail ? (props || this.props).params.objectiveId : this.props.objectiveId;

    this.props.actions.reFetchOkrComments(objectiveId, args, cb);
  }

  fetchMore() {
    this.setState({
      fetching: true
    });

    const args = this.props.editObjectiveDetail ? {
      pageSize,
      pageNumber: this.props.okr.commentsIndex,
    } : {
      pageSize,
      pageNumber: this.props.okr.commentsIndex,
      keyResultId: this.props.keyResultId,
    };

    this.props.actions.fetchOkrComments(this.props.objectiveId, args, () => {
      this.setState({
        fetching: false,
      })
    });
  }

  handleSave() {
    const { comment, currentAmount } = this.state;
    if (this.props.isAutoCalc && !comment) return;
    let arg = {};
    if (!this.props.isAutoCalc) {
      if (`${currentAmount}`.trim()) {
        arg = {
          currentAmount,
        };
      }
    }
    if (comment) {
      arg = {
        ...arg,
        comment,
      }
    }

    if (this.props.editObjectiveDetail) {
      this.props.onClose();
    }
    info('更新中...');

    const { keyResultId, objectiveId } = this.props;
    const cb = () => {
      if (this.props.editObjectiveDetail) {
        if (keyResultId) {
          this.props.refreshKeyResult();
        } else {
          this.props.refreshObjective(true);
        }
      } else {
        this.setState({
          comment: '',
        });
        this.props.fetchObjective();
        this.props.actions.reFetchOkrComments(objectiveId, { pageSize: commentsPageSize, pageNumber: 1, keyResultId });
      }
      success('更新成功!');

      if (!this.props.editObjectiveDetail && this.props.app.naviStep === 5 && this.props.app.guide == 3) {
        this.props.actions.updateGuide(6);
      }
    }

    this.props.actions.addOkrComment({
      keyResultId,
      objectiveId,
      content: arg.comment,
    }, cb)
  }

  updateCurrentAmount(e) {
    let { value } = e.target;
    if (this.props.progressMetricType == 1) {
      value = checkCurrentAmount(value);
      if (value === false) return;
    }
    this.setState({
      currentAmount: value,
    })
  }

  renderInput() {
    const {
      detail,
      currentAmount,
      goalAmount,
      keyResultId,
      objectiveId,
      progressMetricType,
      unit,
      okr,
      active,
      isAutoCalc,
    } = this.props;

    if (detail) return null;
    return (
      <div className={style['input-block']}>
        {
          !this.state.editing ? (
            <Input
              onFocus={() => {this.setState({ editing: true })}}
              label="添加批注.."
              style={{ width: '100%' }}
            />
          ): (
            // 
            <TweetInput
              ref={'kudoTweetInput'}
              onChange={value => this.setState({ comment: value })}
              atList={this.props.atList}
              fetchAtList={keyword => this.props.actions.fetchAtList({ keyword, type: 4 }, "isAt")}
              label="添加批注.." 
              isShowEmoji="false" // 为false时不展示emoji选择链接
              multi
              noBtn
            />
          )
        }
        {/*
          ((!isAutoCalc || keyResultId) && this.state.editing) ?
          <div className={style['input-progress']}>
            <span>{!keyResultId? '目标进度': '关键结果进度'}：</span>
            <Input
              onChange={::this.updateCurrentAmount}
              value={this.state.currentAmount}
              style={{ width: '48px', height: '22px' }}
            />
            {
              progressMetricType == 1?
              <span>%</span>
              : <span style={{ letterSpace: '' }}>/{goalAmount}{unit}</span>
            }
          </div>: null
        */}
        <div className={style['input-actions']}>
          {
            this.state.editing ? (
              <Link
                onClick={() => {
                  this.setState({
                    editing: false,
                  });
                }}
                label="取消"
                style={{ color: '#A9BCCD' }}
              />
            ): null
          }
          {
            this.state.editing ? (
              <Button label="保存" blue onClick={::this.handleSave} />
            ): null
          }
        </div>
      </div>
    );
  }

  renderActions({deletable, editable, okrCommentId, content}) {
    //if (!this.props.detail) return null;
    if (!editable && !deletable) return null;
    if(!this.props.detail) {
      return (
        <div className={style['alert-edit']}>
          <div className={style['alert-link']} onClick={this.handleEditComment.bind(this,okrCommentId,content)}>编辑</div>
          <CommentDeleteAlert id={okrCommentId} onClick={::this.deleteComment} />
        </div>
      );
    }else
      return (
        <Menu
          className={cx(style['comment-actions-menu'], {
            [style.small]: !this.props.detail,
          })}
        >
          <IconButton
            style={{ color: '#8fa6bf', fontSize: '12px' }}
            icon="arrow"
          />
          <EditComment
            editable={editable}
            deletable={deletable}
            okrCommentId={okrCommentId}
            handleEditComment={::this.handleEditComment}
            requestDeleteComment={::this.requestDeleteComment}
            content={content}
          />
        </Menu>
      );
  }

  renderComments() {
    const { okr, editObjectiveDetail } = this.props;
    if (editObjectiveDetail) return null;
    let {
      comments,
    } = okr;

    if (Array.isArray(comments)) {
      // 目标过滤掉kr的内容
      if (!this.props.keyResultId && !this.props.detail) {
        comments = comments.filter(c => !c.keyResultContent);
      }
    }


    // no data
    if (Array.isArray(comments) && !(!this.props.detail ? comments.filter(c => c.content) : comments).length) {
      if (this.props.detail) {
        return (
          <div style={{ height: '237px' }}>
            <img src={`${IMAGES_PATH}/comment-null.png`} style={{ paddingTop : '22px', margin: 'auto', display: 'block' }}/>
            <p style={{ textAlign: 'center',marginTop: '15px', fontSize: '12px', color: '#777' }}>暂无数据</p>
          </div>
        )
      }
    }

    // loading
    if (!Array.isArray(comments)) {
      if (this.props.detail) {
        return <Loading small style={{ marginLeft: '15px', marginTop: '10px' }} />;
      }
      return null;
    }

    return (
      <ul ref="list" className={style.comments}>
        {
          (!this.props.detail ? comments.filter(c => c.content) : comments).map(({ createdTime, okrUpdateLogVOs, content, editable, okrCommentId, actorUserProfile, deletable, keyResultContent }, i) => (
            <li key={i} className={cx({
              [style['comment-li']]: !this.props.detail
            })} style={{
              backgroundColor: this.state.edit === okrCommentId ? '#F7F9FD' : '#fff',
            }}>
              <div>
                { this.renderActions({deletable, editable, okrCommentId, content}) }
                <div className={style.user}>
                  <Link to={`/okr/objective-targetAll?userId=${actorUserProfile.userId}`} target="_blank">
                    <Avatar
                      width={36}
                      src={actorUserProfile.avatarUrl}
                    />
                  </Link>
                  <div>
                    <p>
                      <Link
                        label={actorUserProfile.fullName}
                        to={`/okr/objective-targetAll?userId=${actorUserProfile.userId}`}
                        target="_blank"
                      />
                    </p>
                    <p style={{ fontSize: '12px', color: '#bbb' }}>{moment(createdTime).fromNow()}</p>
                  </div>
                </div>
                <div className={style.note}>
                  { this.state.edit === okrCommentId? (
                    <div>
                      <Input
                        onChange={::this.handleCommentChange}
                        value={this.state.editComment}
                        multi
                        className={style.input}
                        autoFocus
                      />
                      <div className={style['edit-actions']}>
                        <Link label="取消" onClick={() => {
                          this.setState({
                            edit: null,
                            editComment: '',
                          })
                        }} />
                        <Button blue label="确定" onClick={() => this.updateComment(okrCommentId)} />
                      </div>
                    </div>
                    ): content}
                </div>
                {
                  (keyResultContent && this.props.detail) ?
                  <div className={style['okr-logs-title']}>
                    <IconFont
                      style={{ color: '#D6D6D6', fontSize: '18px' }}
                      value="target"
                    />
                    <span>{keyResultContent}</span>
                  </div>: null
                }
                <div className={style['okr-logs']}>
                  {
                    okrUpdateLogVOs.map((v, i) => (
                      <div key={i}>
                        {/* 
                          (v.title && i == 0 && this.props.detail) ? (
                            <div className={style['okr-logs-title']}>
                              <IconFont
                                style={{ color: '#D6D6D6', fontSize: '18px' }}
                                value="target"
                              />
                              <span>{v.title}</span>
                            </div>
                          ): null
                        */}
                        <div className={style['okr-logs-content']}>
                          <label>{v.attribute}：</label>
                          <span className={style['log-content']}>
                            <span>{v.beforeValue}</span>
                            <IconFont
                              className={style.arrow}
                              value="arrow-long"
                            />
                            <span>{v.afterValue}</span>
                          </span>
                        </div>
                      </div>
                    ))
                  }
                </div>
              </div>
            </li>
          ))
        }
      </ul>
    );
  }

  renderContent() {
    if (!this.props.active) return null;
    return (
      <div>
        { this.renderInput() }
        {
          this.renderComments()
        }
      </div>
    );
  }

  renderMoreButton() {
    
    const { detail, editObjectiveDetail } = this.props;
    const { comments, commentsNumber } = this.props.okr;
    const last = Array.isArray(comments)? commentsNumber - comments.length  : null;

    if (last > 0 && !editObjectiveDetail) {
      return (
        <Button
          disabled={this.state.fetching}
          onClick={::this.fetchMore}
          className={style['fetch-more']}
          style={{ fontSize: '12px', height: '30px', width: '100%', backgroundColor: '#f7f9fd', color: '#rgba(119,147,178,0.7)'  }}
          label={`${last}条已折叠...`}
          blue
          radius="0px"
        />
      );
    }
    return null
  }

  render() {
    const { className, detail } = this.props;
    return (
      <div
        className={cx(style.root, className, {
          [style['objective-detail']]: detail,
        })}
      >
        { this.renderContent() }
        { this.renderMoreButton() }
        <Modal
          active={this.state.deleteComment}
          onRequestClose={::this.cancelDeleteComment}
          actions={[
            'cancel',
            ::this.deleteComment,
          ]}
          title="删除动态"
        >
          <p>确定要删除这条动态吗?</p>
        </Modal>
      </div>
    );
  }
}

export default ObjectiveNote;
